package com.auto.autoapp.ui.sample

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.auto.autoapp.data.model.PageData
import com.auto.autoapp.data.model.User
import com.auto.autoapp.data.repository.UserRepository
import com.auto.autoapp.network.NetworkResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * 用户 ViewModel 示例
 * 展示如何在 ViewModel 中使用网络框架
 */
class UserViewModel : ViewModel() {
    
    private val userRepository = UserRepository()
    
    // 用户列表状态
    private val _userListState = MutableStateFlow<NetworkResult<PageData<User>>>(NetworkResult.Loading)
    val userListState: StateFlow<NetworkResult<PageData<User>>> = _userListState.asStateFlow()
    
    // 用户详情状态
    private val _userDetailState = MutableStateFlow<NetworkResult<User>>(NetworkResult.Loading)
    val userDetailState: StateFlow<NetworkResult<User>> = _userDetailState.asStateFlow()
    
    // 创建用户状态
    private val _createUserState = MutableStateFlow<NetworkResult<User>?>(null)
    val createUserState: StateFlow<NetworkResult<User>?> = _createUserState.asStateFlow()
    
    /**
     * 加载用户列表
     */
    fun loadUserList(page: Int = 1, pageSize: Int = 20) {
        viewModelScope.launch {
            userRepository.getUserList(page, pageSize).collect { result ->
                _userListState.value = result
            }
        }
    }
    
    /**
     * 加载用户详情
     */
    fun loadUserDetail(userId: Int) {
        viewModelScope.launch {
            userRepository.getUserDetail(userId).collect { result ->
                _userDetailState.value = result
            }
        }
    }
    
    /**
     * 创建用户
     */
    fun createUser(name: String, email: String, phone: String? = null) {
        viewModelScope.launch {
            userRepository.createUser(name, email, phone).collect { result ->
                _createUserState.value = result
            }
        }
    }
    
    /**
     * 删除用户
     */
    fun deleteUser(userId: Int, onResult: (Boolean, String?) -> Unit) {
        viewModelScope.launch {
            userRepository.deleteUser(userId).collect { result ->
                when (result) {
                    is NetworkResult.Success -> {
                        onResult(true, null)
                    }
                    is NetworkResult.Error -> {
                        onResult(false, result.message)
                    }
                    is NetworkResult.Loading -> {
                        // 可以显示加载状态
                    }
                }
            }
        }
    }
}


